package com.zimi.util;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zimi.bean.Constants;
import com.zimi.mapper.*;
import com.zimi.model.*;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CommonUtil {
    static final String CONST_ADMIN_FLAG = "adminFlag";
    static final String CONST_ORG_LISTS = "orgList";
    static final String CONST_OGN_IDS = "ognIdList";
    @Autowired
    private SysOrgMapper sysOrgMapper;
    @Autowired
    private SysOrgPartnerMapper sysOrgPartnerMapper;
    @Autowired
    private SysRoleUserMapper sysRoleUserMapper;
    @Autowired
    private SysPostSuperiorsMapper sysPostSuperiorsMapper;
    @Autowired
    private SysOrgExtendMapper sysOrgExtendMapper;

    /*
     * 机构树的共同方法
     * @ognIds 限制机构树的机构根节点一览
     * */
    public List<SysOrgExtend> getOrgPostUser(List<Integer> ognIds) {
        List<SysOrgExtend> result = new ArrayList<>();
        List<Integer> ids = new ArrayList<>();

        // 1)取得机构限制条件
        Map limit = getOrgList();
        List<SysOrg> orgList = null;

        if ((boolean) limit.get(CONST_ADMIN_FLAG)) {
            orgList = sysOrgMapper.selectList(new QueryWrapper<SysOrg>().lambda().eq(SysOrg::getOrgState, 1));
        } else {
            orgList = (List<SysOrg>) limit.get(CONST_ORG_LISTS);
        }

        SysOrgExtend tmpOrgExtend = null;

        if (orgList != null && orgList.size() > 0) {
            SysOrgExtend record = new SysOrgExtend();
            List<SysOrgExtend> list = sysOrgExtendMapper.selectOrgPostList(limit);
            Map<Integer, SysOrg> ognMap = new HashMap<>();

            for (SysOrg so : orgList) {
                // 2)根机构保存到ognMap里
                if (so.getOrgPid() == 0) {
                    ognMap.put(so.getId(), so);
                }

                tmpOrgExtend = new SysOrgExtend();
                tmpOrgExtend.setFlag(1);
                tmpOrgExtend.setId(so.getId());
                tmpOrgExtend.setName(so.getOrgName());
                tmpOrgExtend.setOrgId(so.getId());
                tmpOrgExtend.setOgnId(so.getOgnId());
                tmpOrgExtend.setOrgCateId(so.getOrgCate());
                tmpOrgExtend.setParentId(so.getOrgPid() == null ? 0 : so.getOrgPid());
                tmpOrgExtend.setOrgName(so.getOrgName());
                tmpOrgExtend.setChoiceFlag(false);

                result.add(tmpOrgExtend);
            }

            if (list != null && list.size() > 0) {
                for (SysOrgExtend soe : list) {
                    soe.setId(soe.getPostId());
                    soe.setName(soe.getPostName());
                    soe.setFlag(3);
                    soe.setChoiceFlag(false);
                    soe.setParentId(soe.getOrgId());
                    result.add(soe);
                }
            }

            // 3)设置机构的默认岗位
            for (SysOrg so : orgList) {
                tmpOrgExtend = new SysOrgExtend();
                tmpOrgExtend.setId(0);
                tmpOrgExtend.setFlag(3);
                tmpOrgExtend.setPostId(0);
                tmpOrgExtend.setOrgId(so.getId());
                tmpOrgExtend.setParentId(so.getId());
                tmpOrgExtend.setName(ognMap.get(so.getOgnId()).getPostName());
                tmpOrgExtend.setOrgName(so.getOrgName());
                tmpOrgExtend.setPostName(ognMap.get(so.getOgnId()).getPostName());
                tmpOrgExtend.setChoiceFlag(false);
                result.add(tmpOrgExtend);
            }

            List<SysOrgExtend> userList = sysOrgExtendMapper.selectPostUserList(limit);

            if (userList != null && userList.size() > 0) {
                for (SysOrgExtend soe : userList) {
                    soe.setId(soe.getId());
                    soe.setName(soe.getName());
                    soe.setFlag(5);
                    soe.setPostName(soe.getOrgName() + " - " + soe.getDutyName());
                    soe.setIconType("user");
                    soe.setChoiceFlag(false);
                    result.add(soe);
                }
            }
        }

        // 4)取得并合并机构分类
        List<SysOrgExtend> orgCateList = sysOrgExtendMapper.getMineOgnCateList((List<Integer>) limit.get(CONST_OGN_IDS));

        if (orgCateList != null && orgCateList.size() > 0) {
            for (SysOrgExtend soe : orgCateList) {
                soe.setFlag(0);
                result.add(soe);
            }
        }

        return result;
    }

    /*
     * 取得登陆人的可以看的机构一览
     * */
    public Map getOrgList() {
        Map result = new HashMap();

        Session session = ShiroUtils.getSession();
        SysUser user = (SysUser) session.getAttribute(Constants.USER_SESSION_KEY);//登陆人信息

        boolean admin = (boolean) session.getAttribute(Constants.IS_ADMIN_FLAG);//是否是超级管理员
        result.put(CONST_ADMIN_FLAG, admin);

        List<SysOrg> fullOrgs = null;
        List<Integer> roleOgnIds = null;
        if (!admin) {
            SysPostUser postUser = (SysPostUser) session.getAttribute(Constants.CURENT_POST_USER);//用户机构信息
            SysOrg sysOrg = new SysOrg().selectById(postUser.getOrgId());//登陆人所属机构

            // 1)获取登录人拥有的角色管辖的根机构编号
            roleOgnIds = sysRoleUserMapper.selectMineOrgIdList(postUser.getUserId());

            if (roleOgnIds == null) {
                roleOgnIds = new ArrayList<>();
            }

            // 2)登陆人所属根机构
            roleOgnIds.add(0, sysOrg.getOgnId());

            // 3)登陆人角色管辖的根机构一览可参照的跟机构一览
            List<SysOrgPartner> relationOgns = sysOrgPartnerMapper.selectList(new QueryWrapper<SysOrgPartner>().lambda().eq(SysOrgPartner::getState, 1).eq(SysOrgPartner::getOrgId, sysOrg.getOgnId()));
            if (relationOgns != null & relationOgns.size() > 0) {
                for (SysOrgPartner sop : relationOgns) {
                    roleOgnIds.add(sop.getTargetOrgId());
                }
            }

            // 4)公开的根机构一览
            List<SysOrg> openOgns = sysOrgMapper.selectList(new QueryWrapper<SysOrg>().lambda().eq(SysOrg::getOrgState, 1).eq(SysOrg::getOpen, 1).eq(SysOrg::getOrgPid, 0));

            if (openOgns != null & openOgns.size() > 0) {
                for (SysOrg so : openOgns) {
                    roleOgnIds.add(so.getId());
                }
            }

            // 5)以上根机构的所属机构（包含根机构）
            fullOrgs = sysOrgMapper.selectList(new QueryWrapper<SysOrg>().lambda().eq(SysOrg::getOrgState, 1).in(SysOrg::getOgnId, roleOgnIds));

            // 6)半公开(不包含1,2,3,4)的根机构
            List<SysOrg> harfOpenOgns = sysOrgMapper.selectList(new QueryWrapper<SysOrg>().lambda().eq(SysOrg::getOrgState, 1).eq(SysOrg::getOpen, 2).eq(SysOrg::getOrgPid, 0).notIn(SysOrg::getId, roleOgnIds));

            if (harfOpenOgns != null && harfOpenOgns.size() > 0) {
                List<Integer> harfOgnIds = new ArrayList<>();
                for (SysOrg so : harfOpenOgns) {
                    fullOrgs.add(so);
                    harfOgnIds.add(so.getId());
                }

                roleOgnIds.addAll(harfOgnIds);

                // 7)半公开(不包含1,2,3,4)的根机构的所属机构(不包含根机构)
                harfOpenOgns = sysOrgMapper.selectList(new QueryWrapper<SysOrg>().lambda().eq(SysOrg::getOrgState, 1).ne(SysOrg::getOrgPid, 0).in(SysOrg::getOgnId, harfOgnIds));

                if (harfOpenOgns != null && harfOpenOgns.size() > 0) {
                    fullOrgs.addAll(harfOpenOgns);
                }
            }
        }

        result.put(CONST_ORG_LISTS, fullOrgs);
        result.put(CONST_OGN_IDS, roleOgnIds);

        return result;
    }

    /*
     * 取得登陆人岗位的上级岗位一览
     * */
    public List<SysOrgExtend> getMineOrgPost(SysOrgExtend record) {
        List<SysOrgExtend> result = new ArrayList<>();

        // 1)取得机构限制条件
        Map map = getOrgList();
        List<SysOrg> orgList = sysOrgExtendMapper.selectMineOrgList(map);

        SysOrgExtend tmpOrgExtend = null;

        if (orgList != null && orgList.size() > 0) {
            // 2)取得所选的岗位的上级数据
            Map<String, SysPostSuperiors> superiousMap = new HashMap<>();
            List<SysPostSuperiors> superiousList = sysPostSuperiorsMapper.selectList(new LambdaQueryWrapper<SysPostSuperiors>().eq(SysPostSuperiors::getState, 1).eq(SysPostSuperiors::getOrgId, record.getOrgId()).eq(SysPostSuperiors::getPostId, record.getPostId()));

            if (superiousList != null && superiousList.size() > 0) {
                for (SysPostSuperiors sps : superiousList) {
                    superiousMap.put(String.format("%d-%d", sps.getOriginOrgId(), sps.getPostId()), sps);
                }
            }

            Map<String, Object> limit = new HashMap<>();
            limit.put(CONST_ADMIN_FLAG, false);
            limit.put(CONST_ORG_LISTS, orgList);

            List<SysOrgExtend> list = sysOrgExtendMapper.selectOrgPostList(limit);
            Map<Integer, SysOrg> ognMap = new HashMap<>();
            SysPostSuperiors tmpSuperiors = null;

            for (SysOrg so : orgList) {
                // 2)根机构保存到ognMap里
                if (so.getOrgPid() == 0) {
                    ognMap.put(so.getId(), so);
                }

                tmpOrgExtend = new SysOrgExtend();
                tmpOrgExtend.setFlag(2);
                tmpOrgExtend.setId(so.getId());
                tmpOrgExtend.setName(so.getOrgName());
                tmpOrgExtend.setOrgId(so.getId());
                tmpOrgExtend.setOgnId(so.getOgnId());
                tmpOrgExtend.setOrgCateId(so.getOrgCate());
                tmpOrgExtend.setParentId(so.getOrgPid() == null ? 0 : so.getOrgPid());
                tmpOrgExtend.setOrgName(so.getOrgName());
                tmpOrgExtend.setPostName(so.getPostName());
                tmpOrgExtend.setChoiceFlag(false);

                result.add(tmpOrgExtend);
            }

            if (list != null && list.size() > 0) {
                for (SysOrgExtend soe : list) {
                    soe.setPostId(soe.getPostId());
                    soe.setName(soe.getPostName());
                    soe.setFlag(3);
                    tmpSuperiors = (SysPostSuperiors) superiousMap.get(String.format("%d-%d", soe.getOrgId(), soe.getPostId()));
                    if (tmpSuperiors != null) {
//                        soe.setChoiceFlag(true);
                        soe.setId(tmpSuperiors.getId());
                        soe.setUpdateTime(tmpSuperiors.getUpdateTime());
                    } else {
//                        soe.setChoiceFlag(false);
                        soe.setId(0);
                    }
                    soe.setOrgId(soe.getOrgId());
                    soe.setParentId(soe.getOrgId());
                    result.add(soe);
                }
            }

            // 4)取得并合并机构分类
            List<SysOrgExtend> orgCateList = sysOrgExtendMapper.getMineOgnCateList((List<Integer>) map.get("ognIdList"));

            if (orgCateList != null && orgCateList.size() > 0) {
                result.addAll(orgCateList);
            }
        }

        return result;
    }
}
